#!/bin/bash
#author: xieziqiang
#email: xie.zi.qiang@outlook.com

# https://kafka.apache.org/downloads
#****** vars *********#
KAFKA_VERSION="2.13-3.7.1"
KAFKA_INSTALL_PATH="/usr/local"
JAVA_HOME="/usr/local/jdk"
ZK_CONNECT="127.0.0.1:2181" #  ZK集群添加成 "ip1:2181,ip2:2181,ip3:2181"
#****** functions *********#
color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

judge_current_user () {
    if [ "$(id -u)" = "0" ];then
        color "current user is administrator" 0
    else
        color "current user is not administrator" 1
        exit
    fi
}

judge_java_env () {
    if ${JAVA_HOME}/bin/java -version &> /dev/null;then
        color "java env is existed" 0
    else
        color "java env is not existed!" 1
        exit
    fi
}
process_file () {
    if [ ! -e "kafka_${KAFKA_VERSION}.tgz" ];then
        color "current directory dont exist kafka_${KAFKA_VERSION}.tgz" 1
        exit
    fi

    tar -xvf "kafka_${KAFKA_VERSION}.tgz" -C "${KAFKA_INSTALL_PATH}"
    ln -s ${KAFKA_INSTALL_PATH}/kafka_${KAFKA_VERSION} ${KAFKA_INSTALL_PATH}/kafka
    sed -i "/^zookeeper.connect=localhost:2181/c zookeeper.connect=${ZK_CONNECT}" ${KAFKA_INSTALL_PATH}/kafka/config/server.properties
    cat > /lib/systemd/system/kafka.service <<EOF
[Unit]
Description=kafka.service,version ${KAFKA_VERSION}
After=network.target
[Service]
Type=forking
Environment=JAVA_HOME=${JAVA_HOME}
ExecStart=${KAFKA_INSTALL_PATH}/kafka/bin/kafka-server-start.sh -daemon ${KAFKA_INSTALL_PATH}/kafka/config/server.properties
ExecStop=${KAFKA_INSTALL_PATH}/kafka/bin/kafka-server-stop.sh
[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable kafka
        systemctl start kafka && color "kafka start success" 0 || color "kafka start failed !" 1
}

main () {
    judge_current_user
    judge_java_env
    process_file
}

main